package com.itboye.mengwu.app.ui.mymeng;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Observable;
import java.util.Observer;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.alipay.android.phone.mrpc.core.s;
import com.itboye.config.GlobalConfig;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.DebugLog;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.app.shopcar.swipemenulistview.SwipeMenu;
import com.itboye.mengwu.app.shopcar.swipemenulistview.SwipeMenuCreator;
import com.itboye.mengwu.app.shopcar.swipemenulistview.SwipeMenuItem;
import com.itboye.mengwu.app.shopcar.swipemenulistview.SwipeMenuListView;
import com.itboye.mengwu.app.shopcar.swipemenulistview.SwipeMenuListView.OnMenuItemClickListener;
import com.itboye.mengwu.app.ui.mymeng.personsettings.ActivitySiXinXiangQing;
import com.itboye.mengwu.data.interfaces.IFenSiInterface;
import com.itboye.mengwu.data.model.GoodsListModel;
import com.itboye.mengwu.data.model.PrivateXinMessgebean;
import com.itboye.mengwu.data.model.ShopCarBean;
import com.itboye.mengwu.data.presenter.AddGoodsPresenter;
import com.itboye.mengwu.data.presenter.PrivatePresenter;
import com.itboye.mengwu.data.presenter.ZengGuanzhupresenter;
import com.itboye.mengwu.widget.XListView.IXListViewListener;
import com.tencent.ChatActivity;

public class PrivateLtterActivity extends BaseActivity implements Observer,
		IXListViewListener {
	PrivateAdapter adapter;
	SwipeMenuListView listprivate;
	ArrayList<String> list;
	ImageView back;
	TextView txt_title;
	PrivatePresenter presenter;

	ArrayList<PrivateXinMessgebean.A> messgebean = new ArrayList<PrivateXinMessgebean.A>();
	PrivateXinMessgebean model = new PrivateXinMessgebean();
	String uid;
	String ids;
	String curr_uid;
	String rela_uid;
	int pageNo = 1;
	RelativeLayout nodata;

	@Override
	public int initView() {

		return R.layout.activity_priivateletter;
	}

	@Override
	public void onMyCreate() {
		IntentFilter filter = new IntentFilter("privatemsg");
		registerReceiver(receiver, filter);
		txt_title.setText("聊天");
		showProgressDialog("加载中，请稍后", true);
		listprivate = (SwipeMenuListView) findViewById(R.id.listprivate);

		messgebean = new ArrayList<PrivateXinMessgebean.A>();
		listprivate.setXListViewListener(this);
		listprivate.setPullLoadEnable(true);
		listprivate.setPullRefreshEnable(true);
		uid = SPUtils.get(this, null, SpPublicParams.UID, "") + "";
		curr_uid = SPUtils.get(this, null, SpPublicParams.UID, "") + "";
		presenter = new PrivatePresenter(this);
		model.setUid(uid);
		model.setCurr_uid(curr_uid);
		model.setRela_uid(rela_uid);
		model.setPageNo(pageNo + "");
		presenter.getInfo(model);
		back.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				finish();
			}
		});

		SwipeMenuCreator creator = new SwipeMenuCreator() {

			@Override
			public void create(SwipeMenu menu) {

				SwipeMenuItem deleteItem = new SwipeMenuItem(
						PrivateLtterActivity.this);
				// set item background
				deleteItem.setBackground(new ColorDrawable(Color.rgb(0xF9,
						0x3F, 0x25)));
				deleteItem.setTitle("删除");
				deleteItem.setTitleColor(Color.WHITE);
				// // set item width
				deleteItem.setWidth(dp2px(90));
				deleteItem.setTitleSize(18);
				menu.addMenuItem(deleteItem);

			}
		};
		// set creator
		listprivate.setMenuCreator(creator);
		// step 2. listener item click event
		listprivate.setOnMenuItemClickListener(new OnMenuItemClickListener() {
			@Override
			public void onMenuItemClick(int position, SwipeMenu menu, int index) {

				switch (index) {
				case 0:

					if (curr_uid.equals(messgebean.get(position).getTo_id())) {
						model.setRela_uid(messgebean.get(position).getFrom_id());
						model.setCurr_uid(curr_uid);
						presenter.delete(model);
					} else {
						model.setRela_uid(messgebean.get(position).getTo_id());
						model.setCurr_uid(curr_uid);
						presenter.delete(model);
					}

					break;
				}
			}
		});

		listprivate.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {

				// Intent intent=new
				// Intent(PrivateLtterActivity.this,ChatActivity.class);
				// startActivity(intent);
				Intent intent = new Intent(PrivateLtterActivity.this,
						ActivitySiXinXiangQing.class);
				position = position - 1;
				if (uid.equals(messgebean.get(position).getFrom_id())) {
					intent.putExtra("curr_uid", messgebean.get(position)
							.getFrom_id());
					intent.putExtra("rela_uid", messgebean.get(position)
							.getTo_id());
					intent.putExtra("to_nick", messgebean.get(position)
							.getTo_nick());
				} else if (uid.equals(messgebean.get(position).getTo_id())) {
					intent.putExtra("curr_uid", messgebean.get(position)
							.getTo_id());
					intent.putExtra("rela_uid", messgebean.get(position)
							.getFrom_id());
					intent.putExtra("to_nick", messgebean.get(position)
							.getFrom_nick());
				}

				startActivity(intent);

			}
		});
	}

	BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			DebugLog.v("bytag", ">>>>>>>");
			presenter.getInfo(model);
		}
	};

	@SuppressWarnings("static-access")
	@Override
	public void update(Observable observable, Object data) {

		ResultEntity entity = handlerError(data);
		if (entity != null) {
			if (entity.getEventType() == PrivatePresenter.private_success) {
				if (pageNo == 1) {
					messgebean.clear();
				}
				messgebean.addAll(((PrivateXinMessgebean) entity.getData())
						.getList());
				if (messgebean.size() == 0) {
					nodata.setVisibility(View.VISIBLE);
					listprivate.setVisibility(View.GONE);

				} else {
					listprivate.setVisibility(View.VISIBLE);
					nodata.setVisibility(View.GONE);
				}
				if (adapter == null) {
					adapter = new PrivateAdapter(this, messgebean);
					listprivate.setAdapter(adapter);
				} else {
					adapter.notifyDataSetChanged();
				}
			} else if (entity.getEventType() == PrivatePresenter.delete_success) {
				model.setUid(uid);
				presenter.getInfo(model);
			}

		}
		stopLoad();
		try {
			closeProgressDialog();
		} catch (Exception e) {
			// TODO: handle exception
		}
	}

	public int dp2px(int dp) {
		return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp,
				getResources().getDisplayMetrics());
	}

	class PrivateAdapter extends BaseAdapter {
		Context context;
		ArrayList<PrivateXinMessgebean.A> list;

		public PrivateAdapter(Context context,
				ArrayList<PrivateXinMessgebean.A> list) {
			this.context = context;
			this.list = list;
		}

		@Override
		public int getCount() {

			return list == null ? 0 : list.size();
		}

		@Override
		public Object getItem(int position) {

			return list.get(position);
		}

		@Override
		public long getItemId(int position) {

			return position;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {

			Houder houder;

			if (convertView == null) {
				houder = new Houder();
				convertView = LayoutInflater.from(context).inflate(
						R.layout.item_private, null);
				houder.txtPrivateTitle = (TextView) convertView
						.findViewById(R.id.txtPrivateTitle);
				houder.textPinglunTime = (TextView) convertView
						.findViewById(R.id.textPinglunTime);
				houder.txtprivateCountext = (TextView) convertView
						.findViewById(R.id.txtprivateCountext);
				houder.iv_avatar = (ImageView) convertView
						.findViewById(R.id.iv_avatar);
				convertView.setTag(houder);
			} else {
				houder = (Houder) convertView.getTag();
			}
			if (list.size() == 0 || list.get(position) == null
					|| "".equals(list.get(position))) {
			} else {
				if (uid.equals(list.get(position).getFrom_id())) {

					houder.txtPrivateTitle.setText(list.get(position)
							.getTo_nick());
					houder.textPinglunTime.setText(new SimpleDateFormat(
							"yyyy-MM-dd").format(Long.parseLong(list.get(
							position).getSend_time()) * 1000));
					houder.txtprivateCountext.setText(list.get(position)
							.getContent());
					// XImageLoader.load(GlobalConfig.API_URL +
					// "/picture/index?id="
					// + list.get(position).getTo_head(), houder.iv_avatar);
					if (list.get(position).getTo_head() == null
							|| "".equals(list.get(position).getTo_head())) {

						if ("1".equals(list.get(position).getSex())) {
							// imageView.setImageResource(R.drawable.male);
							houder.iv_avatar.setImageResource(R.drawable.male);
						} else {
							houder.iv_avatar
									.setImageResource(R.drawable.female);
						}
					} else if (!list.get(position).getTo_head()
							.startsWith("http")) {
						XImageLoader.load(GlobalConfig.API_URL
								+ "/picture/index?id="
								+ list.get(position).getTo_head(),
								houder.iv_avatar);
					} else if (list.get(position).getTo_head()
							.startsWith("http")) {
						XImageLoader.load(list.get(position).getTo_head(),
								houder.iv_avatar);

					} else {
						houder.iv_avatar.setImageResource(R.drawable.female);
					}
				} else if (uid.equals(list.get(position).getTo_id())) {
					houder.txtPrivateTitle.setText(list.get(position)
							.getFrom_nick());
					houder.textPinglunTime.setText(new SimpleDateFormat(
							"yyyy-MM-dd").format(Long.parseLong(list.get(
							position).getSend_time()) * 1000));
					houder.txtprivateCountext.setText(list.get(position)
							.getContent());
					// XImageLoader.load(GlobalConfig.API_URL
					// + "/picture/index?id="
					// + list.get(position).getFrom_head(),
					// houder.iv_avatar);
					if (list.get(position).getFrom_head() == null
							|| "".equals(list.get(position).getFrom_head())) {

						if ("1".equals(list.get(position).getSex())) {
							// imageView.setImageResource(R.drawable.male);
							houder.iv_avatar.setImageResource(R.drawable.male);
						} else {
							houder.iv_avatar
									.setImageResource(R.drawable.female);
						}
					} else if (!list.get(position).getFrom_head()
							.startsWith("http")) {
						XImageLoader.load(GlobalConfig.API_URL
								+ "/picture/index?id="
								+ list.get(position).getFrom_head(),
								houder.iv_avatar);
					} else if (list.get(position).getFrom_head()
							.startsWith("http")) {
						Log.e("hu2.13", "");
						XImageLoader.load(list.get(position).getFrom_head(),
								houder.iv_avatar);

					} else {
						houder.iv_avatar.setImageResource(R.drawable.female);
					}
				}
			}

			return convertView;
		}

		class Houder {
			private TextView txtPrivateTitle;
			private TextView textPinglunTime;
			private TextView txtprivateCountext;
			private ImageView iv_avatar;
		}

	}

	@Override
	public void onRefresh() {
		// TODO Auto-generated method stub
		showProgressDialog("正在刷新，请稍后", true);
		pageNo = 1;
		model.setPageNo(pageNo + "");
		presenter.getInfo(model);
	}

	@Override
	public void onLoadMore() {
		// TODO Auto-generated method stub
		showProgressDialog("正在加载，请稍后", true);
		pageNo++;
		model.setPageNo(pageNo + "");
		presenter.getInfo(model);
	}

	public void stopLoad() {
		listprivate.stopLoadMore();
		listprivate.stopRefresh();
	}
}
